// pages/questions/questions.js


Page({
  //1、data------------------------------------------
  data:{
    curIndex:'6d85a2b962b2e8200c12de415931a8d0',
    typeName:[],
    questionList:[],
  
  },
    onLoad: function (options) {
      this.kuList()
      this.findQuestion()
    },
    onShow(){
      this.addCollection()
    },
    selectType(e){
        this.setData({
            curIndex : e.currentTarget.dataset.id
        })
        this.findQuestion();
    },
    kuList(){
      wx.cloud.database().collection('type')
      .get()
      .then(res => {
          console.log("success",res)
          this.setData({
            typeName:res.data,
          })


      }).catch(err => {
          console.log("err",err)
      })
    },
    //查找分类问题
    findQuestion(){
      wx.cloud.database().collection('questbank')
      .where({
        ktype: this.data.curIndex
      })
      .orderBy('_createTime','desc')
      .get()
      .then(res => {
          console.log("success",res)
          this.setData({
            questionList:res.data,
          })
      }).catch(err => {
          console.log("err",err)
      })
    },
    //开始做题
    startQuestion(e){
    wx.navigateTo({
      url: '/pages/questdetail/questdetail?id='+e.currentTarget.dataset.id,
    })

    },
    //把收藏的的添加
 async addCollection(){
    let coll = wx.getStorageSync('coll')
    if(coll==null){
     return
    }

    let db = wx.cloud.database().collection('collection')
   let user = wx.getStorageSync('userInfo') 
   if(user==null){return}
     
   //查询此用户的错题表
    let find = await db.where({
       _openid:user._openid
   }).get()
  console.log(find)

  //判断是否相同的题

  for(let i=0;i<coll.length;i++){
    //  console.log("01")
    for(let j=0;j<find.data.length;j++){
      // console.log("02")
      if(coll[i]==null){break}
      if(find.data[j].questionID==coll[i]._id){
        // console.log("03")
          return
      }
    }

    if(coll[i] != null)
    {
      let questionall= coll[i]
      let questionID = coll[i]._id

        //添加操作
           await db.add({
             data:{
                 questionID,
                 questionall
             }
         })
       }
    }
  },
  onShow(){
    this.addCollection()
  }
})